package com.fenxiangtech.mall.service.impl;

import com.fenxiangtech.mall.dao.ThirdAppDao;
import com.fenxiangtech.mall.dto.SerializeWrapper;
import com.fenxiangtech.mall.entity.ThirdApp;
import com.fenxiangtech.mall.enums.ScopeEnum;
import com.fenxiangtech.mall.exception.UserInvalidException;
import com.fenxiangtech.mall.service.AppTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AppTokenServiceImpl extends TokenServiceImpl implements AppTokenService {

    @Autowired
    private ThirdAppDao thirdAppDao;

    @Override
    public Map<String, String> getAppToken(ThirdApp thirdApp) {
        thirdApp = thirdAppDao.getThirdApp(thirdApp.getAppId(), thirdApp.getAppSecret());
        if (thirdApp == null) {
            throw new UserInvalidException();
        }
        String token = this.grantToken(thirdApp);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("token", token);
        return resultMap;
    }

    private String grantToken(ThirdApp thirdApp) {
        SerializeWrapper<Map> tokenValue = this.prepareCachedValue(thirdApp.getId());
        String token = this.generateToken();
        return this.saveToCache(token, tokenValue);
    }

    private SerializeWrapper<Map> prepareCachedValue(Long uid) {
        Map map = new HashMap<>();
        map.put("uid", uid);
        map.put("scope", ScopeEnum.SUPER.getCode());
        return new SerializeWrapper<>(map);
    }
}
